def PrintlnMsg(value,color) {
	colors = [
		'red'   : "\033[40;31m ${value} \033[0m",
		'blue'  : "\033[47;34m ${value} \033[0m",
		'green' : "\033[40;32m ${value} \033[0m"
	]
	ansiColor('xterm') {
		println(colors[color])
	}
}

def GetBranchName(allow) {
	PrintMsg("检测任务触发分支", 'blue')
	script {
		try {
			if("$ref" != "") {
				println "----------检测 webhook 方式触发-----------"
				env.BranchName = ref - "refs/heads/"
				//BranchName = sh(returnStdout: true, script: "echo ${BranchName}|awk -F '/' '{print \$NF}'").trim()
				println "当前webhook触发的分支是: ${BranchName}，任务只允许分支：${allow} 运行"
				if ("${allow}" != "${BranchName}") {
					PrintMsg("webhook方式触发,分支不为: ${AllowBranch},跳过自动任务执行", 'red')
					env.Workfolw = "NO"
				}
			}
		} catch (err) {
			println("该任务非 webhook 触发")
		}
		if ("${params.GIT_BRANCH}" != "") {
			println "-----------检测手动方式触发------------"
			env.BranchName = "${params.GIT_BRANCH}"
			println "手动触发的分支是: ${BranchName}"
		}
		try {
			if (env.BranchName) {
				println("任务触发分支: ${BranchName}")
			} else {
				PrintMsg('未获取到触发任务的Git分支', 'red')
				env.Workfolw = "NO"
			}
		} catch (err) {
			PrintMsg('未获取到触发任务的Git分支', 'red')
			env.Workfolw = "NO"
		}
	}
}

def CheckoutGit(repo, branch, certificate) {
	script {
		try {
			PrintMsg("检出仓库代码：${repo}, 分支：${branch}", 'green')
			checkout([$class: 'GitSCM', 
				branches: [[name: "${branch}"]], 
				doGenerateSubmoduleConfigurations: false, 
				extensions: [[$class: 'CleanBeforeCheckout']], submoduleCfg: [], 
				userRemoteConfigs: [[credentialsId: "${certificate}", url: "${repo}"]]
			])
		} catch (err) {
			PrintMsg("代码检出失败", 'red')
			currentBuild.result = 'FAILURE'
			throw err
		}
	}
}

def CheckoutSVN(repo, certificate) {
	script {
		try {
			PrintMsg("检出仓库代码：${repo}", 'green')
                    if (params.VersionNum=='latest') {
                        env.CheckVersion=  SVN_URL
                    } else {
                        env.CheckVersion=  SVN_URL + "@" + VersionNum
                    }
                    println "检出代码仓库：${SVN_URL}"
                    checkout([$class: 'SubversionSCM', additionalCredentials: [], 
                        excludedCommitMessages: '', excludedRegions: '', 
                        excludedRevprop: '', excludedUsers: '', 
                        filterChangelog: false, ignoreDirPropChanges: false, 
                        includedRegions: '', locations: [[cancelProcessOnExternalsFail: true, 
                        credentialsId: "${certificate}", depthOption: 'infinity', 
                        ignoreExternalsOption: true, local: '.', remote: CheckVersion ]], 
                        quietOperation: true, workspaceUpdater: [$class: 'UpdateWithCleanUpdater']
                    ])
		} catch (err) {
			PrintMsg("代码检出失败", 'red')
			currentBuild.result = 'FAILURE'
			throw err
		}
	}
}


def CheckoutGitHub(repo, token, branch) {
	script {
		try {
			PrintMsg("检出仓库代码：${repo}, 分支：${branch}", 'green')
			if ("${token}" == "") {
				repoUrl = "https://github.com/" + "${repo}"
			} else {
				repoUrl = "https://" + "${token}" + "@github.com/" + "${repo}"
			}
			checkout([$class: 'GitSCM',
				branches: [[name: "${branch}"]],
				extensions: [[$class: 'CheckoutOption', timeout: 30]],
				userRemoteConfigs: [[url: "${repoUrl}"]]
			])
		} catch (err) {
			PrintMsg("代码检出失败", 'red')
			currentBuild.result = 'FAILURE'
			throw err
		}
	}
}

def UploadFTP(host, remote_path) {
	script {
		try {
			PrintMsg("FTP上传: ${host},远程目录: ${remote_path}", 'green')
			ftpPublisher alwaysPublishFromMaster: false, continueOnError: false, failOnError: false, publishers: [[
				configName: "${host}", transfers: [[
					asciiMode: false, cleanRemote: false, excludes: '', 
					flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, 
					patternSeparator: '[, ]+', remoteDirectory: "${remote_path}", 
					remoteDirectorySDF: false, removePrefix: '', sourceFiles: '*.zip, *.json, *.txt'
				]], 
				usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: false
			]]		
		} catch (err) {
			PrintMsg("FTP 上传失败", 'red')
			currentBuild.result = 'FAILURE'
			throw err
		}
	}
}


def CopySSH(host, remote_path) {
	script {
		try {
			PrintMsg("SSH上传: ${host},远程目录: ${remote_path}", 'green')	
			sshPublisher(publishers: [sshPublisherDesc(
				configName: '${host}', 
				transfers: [sshTransfer(cleanRemote: true, excludes: '', execCommand: 'ls -alrth', 
				execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, 
				patternSeparator: '[, ]+', remoteDirectory: '${remote_path}', 
				remoteDirectorySDF: false, removePrefix: '', sourceFiles: '**/*')], 
				usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: false)
			])
		} catch (err) {
			PrintMsg("SSH 上传失败", 'red')
			currentBuild.result = 'FAILURE'
			throw err
		}
}


def GetUser() {
	script {
		try {
			if ("${user_name}" != "") {
				println "获取 webhook 触发用户"
				env.ToUser = env.user_name
			}
		} catch (err) {
			println "获取手动触发用户"
			wrap([$class: 'BuildUser']) {
				env.ToUser = "${env.BUILD_USER}"
			}
		}
		println "任务触发用户: ${ToUser}"
	}
}



def DockerBuild(images) {
	script {
		try {
			PrintMsg("构建 Docker 镜像： ${images}", 'blue')
			sh "docker build --rm --tag ${images} ."
			PrintMsg("推送 Docker 镜像： ${images}", 'blue')
			sh "docker push ${images}"
			PrintMsg("清理 Docker 镜像： ${images}", 'blue')
			sh "docker rmi -f ${images}"		
		} catch (err) {
			PrintMsg("镜像构建失败", 'red')
			currentBuild.result = 'FAILURE'
			throw err
		}
	}
}

